/* eslint-disable */
import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Form,
  Row,
  Col,
  Select,
  Icon,
  Input,
  Button,
  Tag,
  Modal,
  Divider,
  message,
  Drawer,
  DatePicker,
} from 'antd';
import { connect } from 'dva';
import SlickTable from '@/components/SlickTable';
// import useSlickTable from '@/hooks/useSlickTable';
import { useAntdTable } from '@umijs/hooks';
import { getPageSizeByCardHeight } from '@/utils/utils';
import request from '@/utils/request';

const namespace = 'assemblyConfig';
const { RangePicker } = DatePicker;

const judgeObj = obj => {
  if (Object.keys(obj).length == 0) return true;
  else return false;
};


function RuleExeLog({ size: { height }, form, dispatch }) {
  const [selectedRows, setSelectedRows] = useState([]);
  const [size, setSize] = useState(getPageSizeByCardHeight(height - 64 - 8));
  const { getFieldDecorator } = form;

  const [paramsObj, setParamsObj] = useState({});
  const [visible, setVisible] = useState(false);
  const [status, setStatus] = useState('edit');
  const [exeResultMap, setExeResultMap] = useState([]);

  // 通过dva存当前需要传递的数据
  const savePassData = params => {
    dispatch({
      type: `${namespace}/savePassData`,
      payload: params,
    });
  };

  useEffect(() => {
    // request('pms/StaticDataController/getStaticAttr.do', {
    //   data: {
    //     busiObjNbr: 'RmAssembly',
    //     attrNbr: 'assType',
    //   },
    // }).then(res => {
    //   setAssType(res);
    // }).always(() => setLoading(false));

    const exeResultMap = [
      {'attrValue':'0','attrValueName':'执行成功'},
      {'attrValue':'1','attrValueName':'执行失败'},
      {'attrValue':'-1','attrValueName':'未执行'},
      {'attrValue':'-2','attrValueName':'终止'}

  ]
  setExeResultMap(exeResultMap);

  }, []);

  const getTableData = ({ current, pageSize, paramsObj }) => {
    return request('pmc/pms/RuleCfgController/findAllRuleExeLogs', {
      data: {
        page: current,
        rowNum: pageSize,
        pageNum: current,
        pageSize: pageSize,
        // sortName: '',
        // sortOrder: 'asc',
        // filterCol: 'paramCode,paramName,paramValue,groupCode,groupName',
        ...paramsObj,
      },
    }).then(res => {
      if (res.data  && Array.isArray(res.data.records)) {
        return {
          total: res.data.total,
          data: res.data.records.map(val => {
            const { children, ...rest } = val;
            return rest;
          }),
        };
      }
      return {
        total: 0,
        data: [],
      };
    });
  };

  const { tableProps, refresh } = useAntdTable(
    params => {
      return getTableData({ ...params, pageSize: size, paramsObj });
    },
    [paramsObj, height],
    {
      defaultPageSize: size,
      form,
    }
  );
  const { pagination, ...restTableProps } = tableProps;

  useEffect(() => {
    setSize(getPageSizeByCardHeight(height - 64 - 8));
  }, [height]);

  const submit = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let obj = {};


      for (let item in fieldsValue) {
        if (fieldsValue.createDate !== undefined && fieldsValue.createDate !== null
          && fieldsValue.createDate.length != 0) {
          fieldsValue.exeStartDate = fieldsValue.createDate[0].format('YYYY-MM-DD HH:mm:ss');
          fieldsValue.exeEndDate = fieldsValue.createDate[1].format('YYYY-MM-DD HH:mm:ss');
          obj['exeStartDate'] = fieldsValue.exeStartDate;
          obj['exeEndDate'] = fieldsValue.exeEndDate;
        }
        if (fieldsValue[item] != undefined && fieldsValue[item] != '') {
          obj[item] = `${fieldsValue[item]}`;
        }
      }
      setParamsObj(obj);
    });
  };

  const handleSelectRows = value => {
    setSelectedRows(value);
  };

  const ruleRetry = record => {
    return request('pmc/pms/RuleCfgController/retryRulePlan', {
      data: {
        planId:record.planId,
        ruleId:record.ruleId,
        planCode: record.planCode,
        objectId: record.objectId,
        objectType: record.objectType
      },
    }).then(res => {
      if (res  && res.success) {
        refresh();
         message.success("调用完成");

      }else if(res && res.errCode == '001'){
        message.success("该规则已执行成功");
      }else{
          message.warn("重试失败");
      }

    });
  };

  const onClose = () => {
    setVisible(false);
  };






  const handleReset = () => {
    form.resetFields();
  };

  const columns = [
    {
      title: '方案编码',
      dataIndex: 'planCode',
      ellipsis: true,
    },
    {
      title: '方案名称',
      dataIndex: 'planName',
      ellipsis: true,
    },
    {
      title: '执行方式',
      dataIndex: 'retryModel',
      ellipsis: true,
      render: (text, record) => {
        return (
          <span>
              {record.retryModel == 1?'异步执行':'同步执行'}
          </span>
        );
      },

    },
    {
      title: '规则名称',
      dataIndex: 'ruleName',
      ellipsis: true,
    },

    {
      title: '处理结果',
      dataIndex: 'exeResult',
      ellipsis: true,
       render: (text, record) => {
        return (
          <span>
              {record.exeResult == 0?'处理成功':record.exeResult == 1?"处理失败":record.exeResult == -1?'未执行':'终止'}
          </span>
        );
      },
    },

    {
      title: '请求参数',
      dataIndex: 'requestParam',
      ellipsis: true,
       render: (text, record) => {
        return (
            JSON.stringify(record.requestParam)
        );
      },
    },
    {
      title: '触发事件',
      dataIndex: 'objectType',
      ellipsis: true,
    },
    {
      title: '调用对象标识',
      dataIndex: 'objectId',
      ellipsis: true,
    },
    {
      title: '处理时间',
      dataIndex: 'createDate',
      ellipsis: true,
    },

    {
      title: '操作',
      align: 'center',
      render: (text, record) => {
        return (
          <span>
            <a
              onClick={() => {
                ruleRetry(record);
              }}
            >
              {record.retryModel == 1 && record.exeResult == 1 ?'重试':''}
            </a>


          </span>
        );
      },
    },
  ];

  return (
    <>
      <Card
        title="规则执行日志"
        style={{ minHeight: height }}
        className="cute"
        extra={
          <div style={{ display: 'inline-block' }}>
            {/* <Button
              className="margin-right"
              type="primary"
              onClick={() => {
                handleEdit({});
              }}
            >
             新增
            </Button> */}
          </div>
        }
      >
        <Form className="flow fix-label">
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="方案编码">
                {getFieldDecorator('planCode')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="方案名称">
                {getFieldDecorator('planName')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="规则名称">
                {getFieldDecorator('ruleName')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            </Row>


            <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="处理结果">
                {/* {getFieldDecorator('exeResult')(<Input allowClear placeholder="请输入" />)} */}
                {getFieldDecorator('exeResult')(
                  <Select allowClear placeholder="请选择">
                    {exeResultMap.map(item => {
                      return (
                        <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="调用对象标识">
                {getFieldDecorator('objectId')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="触发事件">
                {getFieldDecorator('objectType')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            </Row>


          <Row gutter={16}>
          <Col span={8}>
            <Form.Item label="发起时间">
              {getFieldDecorator('createDate')(<RangePicker style={{width:'100%'}} format="YYYY-MM-DD HH:mm:ss" allowClear showTime/>)}
            </Form.Item>
          </Col>



            <Col span={16} className="text-right">
              <Button type="primary" onClick={submit}>
                查询
              </Button>
              <Button className="margin-left" onClick={handleReset}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>
        <SlickTable
          style={{ marginTop: 8 }}
         // rowKey={record => record.assId}
          columns={columns}
          {...restTableProps}
          data={{
            pagination: {
              ...pagination,
              pageSize: size,
            },
          }}
        />
      </Card>

    </>
  );
}
export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(RuleExeLog));
